package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcDeviceQrcodeIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcDeviceQrcodeOut;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 二维码处理器
 * @author hehuaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class YkcDeviceQrcodeHandler extends YkcAbstractHandler<YkcDeviceQrcodeIn, YkcDeviceQrcodeOut> {
    @Value("${ykc.device-qrcode-prefix}")
    private String qrcodePrefix;
    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        ByteBuf messageBody = message.getMessageBody();
        Long deviceNo = readDeviceNo(messageBody);
        Boolean result = messageBody.readByte() == 0x00;
        YkcDeviceQrcodeIn ykcDeviceQrcodeIn = new YkcDeviceQrcodeIn(deviceNo, result);
        log.info("ykcDeviceQrcodeIn: {}", ykcDeviceQrcodeIn);
        complete(message.getFrameSerialNo(), ykcDeviceQrcodeIn);
    }

    @Override
    public void write(ByteBuf byteBuf, YkcDeviceQrcodeOut out) {
        writeDeviceNo(byteBuf, out.getDeviceNo());
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(qrcodePrefix.length());
        byteBuf.writeCharSequence(qrcodePrefix, StandardCharsets.UTF_8);
        createCompletableFuture(out.getFrameSerialNo());
    }
}
